package com.layne.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.layne.exception.GlobalException;
import com.layne.mapper.OrderMapper;
import com.layne.pojo.Order;
import com.layne.pojo.SeckillGoods;
import com.layne.pojo.SeckillOrder;
import com.layne.pojo.User;
import com.layne.service.IGoodsService;
import com.layne.service.IOrderService;
import com.layne.service.ISeckillGoodsService;
import com.layne.service.ISeckillOrderService;
import com.layne.utils.MD5Utils;
import com.layne.utils.RedisUtil;
import com.layne.utils.UUIDUtil;
import com.layne.vo.GoodsVo;
import com.layne.vo.OrderDetailVo;
import com.layne.vo.RespBeanEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author layne
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private ISeckillGoodsService seckillGoodsService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 秒杀
     * @param user
     * @param goods
     * @return
     */
    @Transactional
    @Override
    public Order seckill(User user, GoodsVo goods) {
        //秒杀商品表减库存
        SeckillGoods one = seckillGoodsService.getOne(new QueryWrapper<SeckillGoods>().eq("goods_id", goods.getId()));
        one.setStockCount(one.getStockCount()-1);

//        boolean rst = seckillGoodsService.update(new UpdateWrapper<SeckillGoods>().set("stock_count", one.getStockCount())
//                .eq("id", one.getId())
//                .gt("stock_count", 0));
        boolean rst = seckillGoodsService.update(new UpdateWrapper<SeckillGoods>().setSql("stock_count=stock_count-1")
                .eq("goods_id", goods.getId()).gt("stock_count", 0));
        if(one.getStockCount()<1){
            //判断是否还有库存
            redisUtil.set("isStockEmpty:" + goods.getId(),"0");
            return null;
        }

        //生成订单
        Order order = new Order();
        order.setUserId(user.getId())
                .setGoodsId(goods.getId())
                .setDeliveryAddrId(0L)
                .setGoodsName(goods.getGoodsName())
                .setGoodsCount(1)
                .setGoodsPrice(one.getSeckillPrice())
                .setOrderChannel(1)
                .setStatus(0)
                .setCreateDate(new Date());
        orderMapper.insert(order);

        //生成秒杀订单
        SeckillOrder skorder = new SeckillOrder();
        skorder.setGoodsId(goods.getId())
                .setUserId(user.getId())
                .setOrderId(order.getId());
        seckillOrderService.save(skorder);

        redisUtil.set("order:"+user.getId()+":"+goods.getId(),skorder);

        return order;
    }

    /**
     * 获得订单详情
     * @param orderId
     * @return
     */
    @Override
    public OrderDetailVo detail(Long orderId) {
        if (orderId == null) {
            throw new GlobalException(RespBeanEnum.ORDER_NOT_EXIST);
        }
        Order order = orderMapper.selectById(orderId);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(order.getGoodsId());
        OrderDetailVo detail = new OrderDetailVo();
        detail.setOrder(order);
        detail.setGoodsVo(goodsVo);
        return detail;
    }

    @Override
    public boolean checkCaptcha(User user, Long goodsId, String captcha) {
        if (user == null || goodsId < 0 || StringUtils.isEmpty(captcha)) {
            return false;
        }
        String redisCaptcha = (String) redisUtil.get("captcha:" + user.getId() + ":" + goodsId);
        return captcha.equals(redisCaptcha);
    }


    /**
     * 获取秒杀接口地址
     * @param user
     * @param goodsId
     * @return
     */
    @Override
    public String createPath(User user, Long goodsId) {
        String str = MD5Utils.md5(UUIDUtil.uuid() + "123456");
        redisUtil.set("seckillPath:" + user.getId() + ":" + goodsId, str, 60);
        return str;
    }

    @Override
    public boolean checkPath(User user, Long goodsId, String path) {
        if (user == null || goodsId < 0 || StringUtils.isEmpty(path)) {
            return false;
        }
        String redisPath = (String) redisUtil.get("seckillPath:" + user.getId() + ":" + goodsId);
        return path.equals(redisPath);
    }
}
